package com.alvin.abp.common.util;

import java.util.Date;

import com.alvin.abp.common.context.CurrentUserContext;
import com.alvin.abp.domain.AbstractEntity;

public abstract class AuditUtils {
	
	public static String appendUserstampSql(String sql) {
		return sql.startsWith("INSERT")?appendInsertStamp(sql):appendUpdatestamp(sql);
	}
	
	public static void populateUserstamp(AbstractEntity entity) {
		Date now = new Date();
		if(CurrentUserContext.getCurrentUser() != null){
			if(entity.getId()==null){
				entity.setCreatedBy(1l);
				entity.setDateCreated(now);
			}
			entity.setUpdatedBy(1l);
			entity.setDateUpdated(now);
		}
	}

	private static String appendUpdatestamp(String sql) {
		StringBuffer result = new StringBuffer();
		result.append(sql.substring(0, sql.indexOf("WHERE")));
		result.append(",updated_by=:updatedBy,date_updated=:dateUpdated ");
		result.append(sql.substring(sql.indexOf("WHERE")));

		
		return result.toString();
	}
	
	private static String appendInsertStamp(String sql) {
		StringBuffer result = new StringBuffer();
		int pos = sql.indexOf(')');
		result.append(sql.substring(0, pos));
		result.append(",date_created,created_by,date_updated,updated_by");
		int pos2 = sql.lastIndexOf(')');
		result.append(sql.substring(pos, pos2));
		result.append(",:dateCreated,:createdBy,:dateUpdated,:updatedBy");
		result.append(sql.substring(pos2));
		return result.toString();
	}
	
	

}
